﻿using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace GameLauncher.Runtime
{
    public partial class Launcher
    {
        public const string EntryType = "Hotfix.Runtime.GameEntry";
        public const string EntryMethod = "Entrance";

        public static bool TryLaunchGame(Assembly mainAssembly, List<Assembly> hotfixAssemblies)
        {
            try
            {
                ValidateAssembly(mainAssembly);
                var entryType = GetEntryType(mainAssembly);
                var entryMethod = GetEntryMethod(entryType);
                InvokeEntry(entryMethod, hotfixAssemblies);
                return true;
            }
            catch (Exception e)
            {
                Debug.LogError($"游戏启动失败: {e.Message}");
                return false;
            }
        }

        private static void ValidateAssembly(Assembly assembly)
        {
            if (assembly == null)
                throw new ArgumentNullException(nameof(assembly), "主程序集不能为空");
        }

        private static Type GetEntryType(Assembly assembly)
        {
            return assembly.GetType(EntryType) ?? throw new TypeLoadException($"未找到入口类型: {EntryType}");
        }

        private static MethodInfo GetEntryMethod(Type entryType)
        {
            return entryType.GetMethod(EntryMethod) ?? throw new MissingMethodException($"未找到入口方法: {EntryMethod}");
        }

        private static void InvokeEntry(MethodInfo method, List<Assembly> hotfixAssemblies)
        {
            var assemblyArray = hotfixAssemblies.ToArray();
            var parameters = new object[] { assemblyArray };
            method.Invoke(null, parameters);
        }
    }
}